<?php

namespace App\Service;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

use Config;

class WeChat {

    public function __construct()
    {
        
    }

    public static function getAccessToken() 
    {

        if(Cache::has('access_token')) {
            $res = Cache::get('access_token');
        }else{
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.Config::get('wechat.APPID').'&secret='.Config::get('wechat.APPSECRET');
            $res = self::httpGet($url);
            if(isset($res['access_token'])){
                Cache::put('access_token',$res,7200);
            }
        }
        return $res['access_token'];
    }

    public static function createMenu() 
    {
        $access_token = self::getAccessToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;

        $data = '{
            "button": [
                {
                    "name": "真伪查询", 
                    "sub_button": [
                        {
                            "type": "scancode_waitmsg", 
                            "name": "扫码验证", 
                            "key": "scancode_waitmsg_0"
                        },
                        {
                            "type": "click", 
                            "name": "手输验证", 
                            "key": "click_0"
                        }
                    ]
                }
            ]
        }';
        $res = self::httpPost($url,$data);

        print_r($res);die;

        
    }

    /*
     * 输出xml响应报头，纯文本
     */
    public static function resonseText($fromUsername, $toUsername, $contentStr)
    {
        //组织xml报头
        $msgType = "text";
        $time = time();
        $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, self::pregstring(strip_tags($contentStr, '<a>')));
        echo $resultStr;
    }

    //文本回复替换特殊字符
    public static function pregstring($str)
    {
        $strtemp = trim($str);
        $search = [
            "|,|Uis",
            "|[\s]{2,}|is",
            "[&nbsp;]isu",
            "[&amp;nbsp;]isu",
            "|[$]|Uis",
            "|<script[^>].*?</script>|Uis",
            // 去掉 javascript
            "'&(quot|#34);'i",
            // 替换 HTML 实体
            "'&amp;(amp|#38);'i",
            "'&amp;(amp|#[0-9]{1,}|[a-zA-Z0-9]{1,});'i",
            "'&(amp|#[0-9]{1,}|[a-zA-Z0-9]{1,});'i",
        ];
        $replace = [
            " ",
            " ",
            " ",
            " ",
            "",
            "",
            "",
            "",
            "",
            "",
        ];
        $text = preg_replace($search, $replace, $strtemp);

        return $text;
    }

    private static function httpGet($url) 
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
    
        $res = curl_exec($curl);
        curl_close($curl);
    
        return json_decode($res, 1);
      }

      private static function httpPost($url,$data) 
      {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    
        $res = curl_exec($curl);
        curl_close($curl);
    
        return $res;
      }

    /**
     * http request
     * @param string $url 请求地址
     * @param array  $data $data为空为get请求 反之则为post
     * @param string $array false 不转array
     * @return string $body json 字符串
     */
    public static function http_request($url, $data = '', $array = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//30秒超时
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $body = curl_exec($ch);
        curl_close($ch);
        if (!$array) {
            $body = json_decode($body, 1);
        }

        return $body;
    }
    

}